package com.itheima.reggie.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.reggie.dto.OrderDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.*;
import com.itheima.reggie.service.OrderService;
import com.itheima.reggie.util.UUIDUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: dw
 * @Date 2022/3/17 18:52
 */
@Service
public class OrderServiceImpl implements OrderService {
    //地址对象
    @Autowired(required = false)
    private AddressBookMapper addressBookMapper;
    //订单主表
    @Autowired(required = false)
    private OrderMapper orderMapper;
    //订单子表详细数据
    @Autowired(required = false)
    private OrderDetailMapper orderDetailMapper;
    //用户表
    @Autowired(required = false)
    private UserMapper userMapper;
    //购物车
    @Autowired(required = false)
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired(required = false)
    private HttpSession session;


    /**
     * 新增订单的业务方法
     *
     * @param orders
     * @return
     */
    @Override
    @Transactional
    public boolean addOrder(Orders orders) {
        //获取会话中的id
        Long id = (Long) session.getAttribute("user");
        //获取登录用户id获取购物车所有数据（将购物车的数据写入到订单子表中）
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.findAll(id);
        //根据传递过来默认收获地址id获取地址对象
        AddressBook addressBook = addressBookMapper.getById(orders.getAddressBookId());
        //根据登录用户用户的id获取登录用户对象（得到用户名别名写入到订单数据）
        User user = userMapper.findByUserId(id);

        //完善订单主表的信息
        Integer uid = UUIDUtils.getUUIDInOrderId();//获取唯一的订单号
        orders.setNumber(uid+"");//设置订单号
        orders.setStatus(1);//设置状态 1为待支付
        orders.setUserId(user.getId());//获取下单用户
        orders.setOrderTime(LocalDateTime.now());//设置下单时间
        orders.setCheckoutTime(LocalDateTime.now());//设置支付时间
        orders.setPhone(addressBook.getPhone());//设置用户手机号
        orders.setAddress(addressBook.getDetail());//设置收货地址
        orders.setUserName(user.getName());//设置用户别名
        orders.setConsignee(addressBook.getConsignee());//设置收货人


        //完善订单子表数据
        //创建一个订单子表集合用来保存订单数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        //定义总金额
        BigDecimal total = new BigDecimal("0");

        //遍历购物车内的数据赋值给 orderDetail对象
        for (ShoppingCart shoppingCart : shoppingCartList) {
            //新建一个orderDetail对象
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setName(shoppingCart.getName());//菜品名字或套餐名字
            orderDetail.setImage(shoppingCart.getImage());//图片
            orderDetail.setOrderId(shoppingCart.getId());//订单id
            orderDetail.setDishId(shoppingCart.getDishId());//菜品id
            orderDetail.setSetmealId(shoppingCart.getSetmealId());//套餐id
            orderDetail.setDishFlavor(shoppingCart.getDishFlavor());//口味
            orderDetail.setNumber(shoppingCart.getNumber());//数量
            orderDetail.setAmount(shoppingCart.getAmount());//金额

            //将封装好的orderDetail对象加入orderDetailList
            orderDetailList.add(orderDetail);

            //累加每个商品的金额=数量*单价
            //multiply（）这个是decimal类型的乘法方法
            //add（）这个是decimal类型的加法方法
            //这里new BigDecimal是因为要两个BigDecimal才能相乘
            //将算好的金额再赋值给总金额
            total = total.add(orderDetail.getAmount().multiply(new BigDecimal(orderDetail.getNumber()+"")));
        }

        //将订单主表的总金额完善
        orders.setAmount(total);

        //调用mapper添加订单主表数据
        orderMapper.save(orders);

        //调用mapper添加多条订单子表数据
        orderDetailMapper.saveBatch(orderDetailList);

        //下单完成后，将购物车清空
       shoppingCartMapper.delete(id);

        return true;
    }

    /**
     * 查询指定用户订单分页数据
     *
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public Page<OrderDto> findByPage(Integer page, Integer pageSize) {
        //获取用户id
        Long userId = (Long) session.getAttribute("user");
        //设置当前页和每页页数
        PageHelper.startPage(page,pageSize);
        //调用mapper查询
        List<Orders> ordersList = orderMapper.findByUid(userId);
        //封装PageInfo
        PageInfo<Orders> pageInfo = new PageInfo<>(ordersList);

        //将ordersList封装成 List<OrderDto>对象
        List<OrderDto> orderDtoList = ordersList.stream().map((order -> {
            OrderDto orderDto = new OrderDto();

            //将order对象属性赋值给orderDto
            BeanUtils.copyProperties(order,orderDto);

            //获取当前订单的详情列表
            List<OrderDetail> orderDetailList = orderDetailMapper.findByOid(order.getId());
            //将订单详情数据赋值给orderDto
            orderDto.setOrderDetails(orderDetailList);

            return orderDto;
        })).collect(Collectors.toList());

        //封装自己的分页数据
        Page<OrderDto> pageObj = new Page<>();
        pageObj.setRecords(orderDtoList);
        pageObj.setTotal(pageInfo.getTotal());
        pageObj.setPage(pageInfo.getPageNum());
        pageObj.setPageSize(pageInfo.getPageSize());
        return pageObj;
    }
}
